package cn.steel.controller.buyer;

/**
 * @author: zhaoyuhan
 * @date: 2025/4/28
 * @description: 买家控制器定义
 */

import cn.steel.domain.dto.InventoryUpdateDto;
import cn.steel.domain.dto.ReceiptDto;
import cn.steel.domain.entity.InventoryAnalysis;
import cn.steel.domain.entity.Order;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.OrderDetailVo;
import cn.steel.domain.vo.OrderItemVo;
import cn.steel.domain.vo.OrderListVo;
import cn.steel.domain.vo.ReceiptVo;
import cn.steel.mapper.InventoryAnalysisMapper;
import cn.steel.mapper.OrderMapper;
//import cn.steel.service.InventoryService;
import cn.steel.service.OrderService;
import cn.steel.service.ReceiptService;
import cn.steel.service.SupplierRatingService;
import cn.steel.utils.R;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/buyer")
public class BuyerOrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private InventoryAnalysisMapper inventoryAnalysisMapper;
    @Autowired
    private SupplierRatingService ratingService;
    private static final Logger log = LogManager.getLogger(BuyerOrderController.class);
    @ApiOperation("收货信息页面")
    @GetMapping("/receipt")
    public String receiptPage(Model model,
                              @SessionAttribute(value = "user", required = false) User user,
                              @RequestAttribute(required = false) Long userId) {
        // 如果 userId 未通过 @RequestAttribute 传入，则从 user 中获取
        if (user == null && userId == null) {
            return "redirect:/login?url=/buyer/receipt";
        }
        Long effectiveUserId = userId != null ? userId : user.getId();
        List<ReceiptVo> receipts = receiptService.getReceiptList(effectiveUserId);
        log.info("Loaded receipts for userId={}: {}", effectiveUserId, receipts); // 添加日志
        model.addAttribute("receipts", receipts);
        model.addAttribute("userId", effectiveUserId);
        return "buyer/receipt";
    }
    @ApiOperation("设为默认")
    @PostMapping("/setDefault/{id}")
    public String setDefaultReceipt(@PathVariable Long id,
                                    @RequestParam Long userId, // Get userId from form
                                    RedirectAttributes redirectAttributes) {
        try {
            boolean success = receiptService.setDefaultReceipt(id, userId);
            if (success) {
                redirectAttributes.addFlashAttribute("success", "默认地址设置成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "设置默认地址失败: 没有找到对应的收货地址");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "设置默认地址失败: " + e.getMessage());
        }
        return "redirect:/buyer/receipt";
    }
    @ApiOperation("删除已有的收货地址")
    @PostMapping("/deleteReceipt/{id}")
    public String deleteReceipt(@PathVariable Long id,
                                @RequestAttribute Long userId,
                                RedirectAttributes redirectAttributes) {
        boolean deleted = receiptService.deleteReceipt(id, userId);
        if (deleted) {
            redirectAttributes.addFlashAttribute("success", "收货地址删除成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "收货地址删除失败");
        }
        return "redirect:/buyer/receipt";
    }
    @ApiOperation("编辑已有的收货地址")
    @GetMapping("/editReceipt/{id}")
    public String editReceiptPage(@PathVariable Long id,
                                  @RequestAttribute Long userId,
                                  Model model) {
        ReceiptVo receipt = receiptService.getReceiptDetail(id, userId);
        if (receipt == null) {
            return "redirect:/buyer/receipt";
        }
        model.addAttribute("receipt", receipt);
        model.addAttribute("userId", userId);
        return "buyer/editReceipt";
    }
    @ApiOperation("更新现有的收获地址")
    @PostMapping("/updateReceipt/{id}")
    public String updateReceipt(@PathVariable Long id,
                                @RequestAttribute Long userId,
                                ReceiptDto receiptDto,
                                RedirectAttributes redirectAttributes) {
        try {
            boolean updated = receiptService.updateReceipt(userId, id, receiptDto);
            if (updated) {
                redirectAttributes.addFlashAttribute("success", "收货地址更新成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "收货地址更新失败");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/buyer/receipt";
    }
    @ApiOperation("提交收货地址")
    @PostMapping("/submitReceipt")
    public String submitReceipt(@RequestAttribute Long userId,
                                ReceiptDto receiptDto,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        try {
            Long receiptId = receiptService.saveReceipt(userId, receiptDto);
            Long pendingOrderId = (Long) session.getAttribute("pendingOrderId");

            if (pendingOrderId != null) {
                // 获取刚保存的收货地址
                ReceiptVo receipt = receiptService.getReceiptDetail(receiptId, userId);
                Order order = orderMapper.getOrderById(pendingOrderId);
                if (order != null && order.getBuyerId().equals(userId)) {
                    // 更新订单的收货信息
                    order.setDeliveryAddress(receipt.getDeliveryAddress());
                    order.setContactName(receipt.getContactName());
                    order.setContactPhone(receipt.getContactPhone());
                    orderMapper.update(order);

                    // 清除 session 中的 pendingOrderId
                    session.removeAttribute("pendingOrderId");

                    redirectAttributes.addFlashAttribute("success", "收货地址提交成功");
                    return "redirect:/buyer/detail/" + order.getOrderNo();
                }
            }

            redirectAttributes.addFlashAttribute("success", "收货地址提交成功");
            return "redirect:/buyer/list";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "收货地址提交失败: " + e.getMessage());
            return "redirect:/buyer/receipt";
        }
}
    @PostMapping("/useReceipt/{id}")
    public String useReceipt(@PathVariable Long id,
                             @RequestAttribute Long userId,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        ReceiptVo receipt = receiptService.getReceiptDetail(id, userId);
        if (receipt == null) {
            redirectAttributes.addFlashAttribute("error", "地址不存在或不属于当前用户");
            return "redirect:/buyer/receipt";
        }

        Long pendingOrderId = (Long) session.getAttribute("pendingOrderId");
        if (pendingOrderId != null) {
            Order order = orderMapper.getOrderById(pendingOrderId);
            if (order != null && order.getBuyerId().equals(userId)) {
                order.setDeliveryAddress(receipt.getDeliveryAddress());
                order.setContactName(receipt.getContactName());
                order.setContactPhone(receipt.getContactPhone());
                log.info("Updating order with receipt: orderId={}, contactName={}, contactPhone={}, deliveryAddress={}",
                        pendingOrderId, receipt.getContactName(), receipt.getContactPhone(), receipt.getDeliveryAddress());
                orderMapper.update(order);
                session.removeAttribute("pendingOrderId");

                redirectAttributes.addFlashAttribute("success", "已选择地址: " + receipt.getContactName());
                return "redirect:/buyer/detail/" + order.getOrderNo();
            } else {
                log.warn("Invalid order or user mismatch for orderId={}", pendingOrderId);
            }
        } else {
            log.warn("pendingOrderId is null, cannot update order receipt for userId={}", userId);
        }

        session.setAttribute("selectedReceiptId", id);
        redirectAttributes.addFlashAttribute("success", "已选择地址: " + receipt.getContactName());
        return "redirect:/buyer/list";
    }

    @GetMapping("/list")
    public String orderList(Model model,
                            @RequestAttribute Long userId,
                            @RequestParam(required = false) String status,
                            @RequestParam(required = false) String orderNo,
                            @RequestParam(defaultValue = "1") int pageNum,
                            @RequestParam(defaultValue = "5") int pageSize,
                            HttpSession session) {
        Long pendingOrderId = (Long) session.getAttribute("pendingOrderId");
        if (pendingOrderId != null) {
            status = null;
        }

        Long selectedReceiptId = (Long) session.getAttribute("selectedReceiptId");
        log.info("Retrieved selectedReceiptId from session: id={}", selectedReceiptId); // 添加日志

        ReceiptVo selectedAddress = null;
        if (selectedReceiptId != null) {
            selectedAddress = receiptService.getReceiptDetail(selectedReceiptId, userId);
            log.info("Loaded selectedAddress for selectedReceiptId={}: {}", selectedReceiptId, selectedAddress); // 添加日志
        } else {
            selectedAddress = receiptService.getDefaultReceipt(userId);
            log.info("Loaded default address for userId={}: {}", userId, selectedAddress); // 添加日志
        }

        model.addAttribute("selectedAddress", selectedAddress);

        if (orderNo != null && !orderNo.isEmpty()) {
            OrderDetailVo detail = orderService.getOrderDetail(orderNo, userId);
            List<OrderListVo> orders = detail != null ? List.of(convertToOrderListVo(detail)) : List.of();
            model.addAttribute("orders", orders);
            model.addAttribute("pageInfo", new PageInfo<>(orders));
        } else {
            PageInfo<OrderListVo> pageInfo = orderService.getPagedOrderList(userId, status, pageNum, pageSize);
            model.addAttribute("orders", pageInfo.getList());
            model.addAttribute("pageInfo", pageInfo);
        }

        model.addAttribute("status", status);
        model.addAttribute("orderNo", orderNo);
        return "buyer/list";
    }


    private OrderListVo convertToOrderListVo(OrderDetailVo detail) {
        OrderListVo vo = new OrderListVo();
        BeanUtils.copyProperties(detail, vo);
        return vo;
    }

    @GetMapping("/detail/{orderNo}")
    public String orderDetail(Model model, @PathVariable String orderNo,
                              @RequestAttribute Long userId) {
        OrderDetailVo order = orderService.getOrderDetail(orderNo, userId);

        if (order == null) {
            model.addAttribute("error", "订单不存在或无权限查看");
            return "buyer/detail";
        }

        log.info("Order detail: {}, items: {}", order, order.getItems());
        model.addAttribute("order", order);
        boolean canRate = ratingService.canRateOrder(order.getId(), userId);
        model.addAttribute("canRate", canRate);
        return "buyer/detail";
    }

@PostMapping("/pay/{orderNo}")
@Transactional
public ResponseEntity<Map<String, Object>> payOrder(
        @PathVariable String orderNo,
        @RequestParam String paymentMethod,
        @RequestAttribute Long userId) {

    Map<String, Object> response = new HashMap<>();
    try {
        // 1. 获取订单
        Order order = orderMapper.getOrderByOrderNo(orderNo);
        if (!"PENDING".equals(order.getStatus())) {
            throw new RuntimeException("只有待支付订单才能支付");
        }

        // 2. 规范化 paymentMethod
        paymentMethod = paymentMethod.toUpperCase(); // 转换为大写
        if (!"BANK_TRANSFER".equals(paymentMethod) &&
                !"ONLINE_PAYMENT".equals(paymentMethod) &&
                !"CREDIT".equals(paymentMethod)) {
            throw new RuntimeException("支付方式无效，必须是 BANK_TRANSFER, ONLINE_PAYMENT 或 CREDIT");
        }

        // 3. 检查库存
        OrderDetailVo orderDetail = orderService.getOrderDetail(orderNo, userId);
        for (OrderItemVo item : orderDetail.getItems()) {
            InventoryUpdateDto dto = new InventoryUpdateDto();
            dto.setProductId(item.getProductId());
            dto.setQuantity(item.getQuantity());

            InventoryAnalysis inventory = inventoryAnalysisMapper.selectByProduct(dto.getProductId());
            if (inventory == null || inventory.getInventory() < dto.getQuantity()) {
                throw new RuntimeException("商品ID:" + item.getProductId() + "库存不足");
            }
        }

        // 4. 更新订单状态
        order.setPaymentMethod(paymentMethod);
        order.setStatus("PAID");
        order.setPaymentTime(new Date());
        orderMapper.update(order);

        // 5. 扣减库存
        for (OrderItemVo item : orderDetail.getItems()) {
            InventoryUpdateDto dto = new InventoryUpdateDto();
            dto.setProductId(item.getProductId());
            dto.setQuantity(item.getQuantity());

            if (!orderService.reduceInventory(dto)) {
                throw new RuntimeException("减少库存失败，商品ID:" + item.getProductId());
            }
        }

        response.put("success", true);
        response.put("message", "支付成功");
        response.put("redirectUrl", "/buyer/detail/" + orderNo);
        return ResponseEntity.ok(response);
    } catch (Exception e) {
        log.error("支付失败", e);
        response.put("success", false);
        response.put("message", "支付失败: " + e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }
}

    @ApiOperation("取消支付")
    @PostMapping("/cancel/{orderNo}")
    public String cancelOrder(@PathVariable String orderNo, @RequestAttribute Long userId) {
        orderService.cancelOrder(orderNo, userId);
        return "redirect:/buyer/detail/" + orderNo;
    }

    @ApiOperation("确认收货")
    @PostMapping("/confirm/{orderNo}")
    public String confirmReceipt(@PathVariable String orderNo,
                                 @RequestAttribute Long userId,
                                 RedirectAttributes redirectAttributes) {
        try {
            boolean success = orderService.confirmReceipt(orderNo, userId);
            if (!success) {
                redirectAttributes.addFlashAttribute("error", "确认收货失败：订单状态不符合要求");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "确认收货失败：" + e.getMessage());
        }
        return "redirect:/buyer/detail/" + orderNo;
    }

    @PostMapping("/delete/{orderNo}")
    public String deleteOrder(@PathVariable String orderNo,
                              @RequestAttribute Long userId,
                              RedirectAttributes redirectAttributes) {
        // 获取订单详细信息
        OrderDetailVo order = orderService.getOrderDetail(orderNo, userId);

        // 仅允许删除已完成和已取消的订单
        if (order == null) {
            redirectAttributes.addFlashAttribute("error", "订单不存在");
            return "redirect:/buyer/list";
        }

        if ("COMPLETED".equals(order.getStatus()) || "CANCELLED".equals(order.getStatus())) {
            try {
                // 执行删除操作
                orderService.deleteOrder(orderNo);
                redirectAttributes.addFlashAttribute("success", "订单删除成功");
            } catch (Exception e) {
                redirectAttributes.addFlashAttribute("error", "删除失败: " + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "只能删除已完成或已取消的订单");
        }

        return "redirect:/buyer/list";
    }
}